﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace BaseUi
{
    public static class EnumHelps
    {
        /// <summary>
        /// 得到枚举的所有名称
        /// </summary>
        /// <param name="type">枚举</param>
        /// <returns>所有名称</returns>
        public static List<string> GetEnumNames(Type type)
        {
            List<string> strings = new List<string>();
            if (type.IsEnum)
            {
                var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public) ?? new FieldInfo[] { };
                foreach (var field in fields)
                {
                    strings.Add(field.Name);
                }
            }
            return strings;
        }

        /// <summary>
        /// 得到枚举详情
        /// </summary>
        /// <param name="type">枚举</param>
        /// <param name="isDescriptionNullInName">描述为空时，是否采用名称值</param>
        /// <returns>枚举值，名称，描述</returns>
        public static List<Tuple<int, string, string>> GetEnumDescriptionList(Type type, bool isDescriptionNullInName = false)
        {
            var strings = new List<Tuple<int, string, string>>();
            if (type.IsEnum)
            {
                var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
                if (fields == null)
                    return strings;

                foreach (var field in fields)
                {
                    int enumValue = Convert.ToInt32(field.GetRawConstantValue());
                    string enumName = field.Name;
                    string description = string.Empty;

                    var descriptionAttribute = field.GetCustomAttribute<DescriptionAttribute>(false);
                    if (descriptionAttribute != null)
                        description = descriptionAttribute.Description;
                    else if (isDescriptionNullInName)
                        description = enumName;

                    strings.Add(new Tuple<int, string, string>(enumValue, enumName, description));
                }
            }
            return strings;
        }
    }
}
